ProgressView = require './utils/progress-view'
_ = require 'underscore'
{openDirectory} = require('./utils/dialog')
#{generateKeyPair} = require './utils/gitApi'
UUID = require 'uuid'
fs = require 'fs'
# for debug properse only, it will add many ms to startup time.
Q = require 'q'
Q.longStackSupport = true

module.exports =

  configDefaults:
    chameleonServerAddress: 'http://bsl.foreveross.com'
    chameleonTanant: 'cube'
    chameleonUsername: 'cube'
    puzzleServerAddress: 'http://bsl.foreveross.com/puzzle' # http://localhost:8000/puzzle
    puzzleServerAddressSecured: 'https://bsl.foreveross.com/puzzle' # https://localhost:8443/puzzle
    puzzleAccessToken: ''
    gitCloneEnvironmentPath: ''

  activate: (state) ->
    console.log("atwork-qdt avtive")
    localStorage.removeItem 'github' # 重启就要github认证，不然会报错，暂时这样
    localStorage.removeItem 'gogs' # 重启就要gogs认证，不然会报错，暂时这样


    # create access_token if necessary
    token = atom.config.get('atom-chameleon.puzzleAccessToken')
    atom.config.set('atom-chameleon.puzzleAccessToken', UUID.v4()) unless token
    ###
    @projectManager = new (require './project/project-manager')()
    @projectManager.activate()

    @packageManager = new (require './package/package-manager')()
    @packageManager.activate()

    @fileManager = new (require './file/file-manager')()
    @fileManager.activate()

    @buildManager = new (require './build/build-manager')()
    @buildManager.activate()
    ###
    @emulatorManager = new (require './emulator/emulator-manager')()
    @emulatorManager.activate()
    ###
    @gitCreatePackageManager = new (require './gitCreatePackage/gitCreatePackage-manager')()
    @gitCreatePackageManager.activate()

    @packageCenterManager = new (require './package/package-center-manager')
    @packageCenterManager.activate()
    ###
    atom.workspaceView.command "atom-chameleon:debug", => @cmdDebug()
    atom.workspaceView.command "atom-chameleon:debug-emulator", => @cmdDebugEmulator()

    #New
    atom.workspaceView.command "atom-chameleon:create-project", => @cmdCreateProject()

    atom.workspaceView.command "atwork-qdt:help-amazeui-doc", => @openAmazeUIDoc()
    atom.workspaceView.command "atwork-qdt:help-butterfly-doc", => @openButterflyDoc()


  deactivate: ->

    @projectManager.deactivate?()
    #@packageManager.deactivate?()
    #@fileManager.deactivate?()
    #@buildManager.deactivate?()
    @emulatorManager.deactivate?()
    #@gitCreatePackageManager.deactivate?()

  openAmazeUIDoc: ->
    (require './help/amazeui-doc').open()

  openButterflyDoc: ->
    (require './help/butterfly-doc').open()

  cmdDebugEmulator: ->
    try
      webview = document.querySelector('webview')
      # console.log "webview.isDevToolsOpened(): #{webview.isDevToolsOpened()}"
      if webview.isDevToolsOpened()
        webview.closeDevTools()
      else
        webview.openDevTools()
    catch
      console.log "webview not open"


  cmdDebug: ->
    # BowerView = require './scaffold/bower-view'
    # new BowerView().attach()
    # webview = document.querySelector('webview')
    # webview.openDevTools() unless webview.isDevToolsOpened()

    bsv = new (require './build/build-state-view')()
    bsv.attach()

  cmdCreateProject: ->

    ProjectWizardView = require './project/project-wizard-view'
    projectWizardView = new ProjectWizardView().attach()
    pv = new ProgressView("Create Project...")

    Q.Promise (resolve, reject, notify) =>
      isOpenDialog = false
      projectWizardView.on 'finish', (result) ->
        if isOpenDialog
          return
        isOpenDialog = true
        # composite promise combine result with previous result
        openDirectory(title: 'Select Path')
        .then (destPath) ->
          resolve _.extend(result, path: destPath[0])
        .finally ->
          isOpenDialog = false

    # do UI stuffs
    .then (options)->
      projectWizardView.destroy()
      pv.attach()
      Q(options)

    # create project with options
    .then (options) ->
      # promise of project creation
      (require "./project/projectFilesGenerator")(options)

    # open new project
    .then (projectPath)->
      atom.open {pathsToOpen: [projectPath]}
      treeView = atom.packages.getActivePackage('tree-view').mainModule.treeView
      if treeView && treeView.isHidden && treeView.isHidden()
        #if atom.packages.getActivePackage('tree-view').mainModule.treeView.isHidden()
        atom.workspaceView.trigger "tree-view:toggle"

    .progress (progress)->
      pv.setTitle(progress.message) if progress.message
      pv.setProgress(progress.progress) if progress.progress
      console.log progress.out if progress.out
    .catch (error) ->
      console.trace error.stack
      alert("#{error}")
    .finally ->
      pv.destroy()
